package cn.wsn2018.tools.service;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.model.VO.UserView;
import cn.wsn2018.tools.util.EncryptUtil;
import cn.wsn2018.tools.util.JsonUtil;
import cn.wsn2018.tools.util.LogUtil;
import cn.wsn2018.tools.util.Regex;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDao userDao;

    /**
     * 业务层,处理用户登录验证
     * @param username 表单提供用户名
     * @param password 表单提供密码
     * @return 登录成功与否的状态(无需返回jsonObject或jsonArray)
     */
    public String dealUserLogin(String username,String password) throws UnsupportedEncodingException {


        if(username!=null&&!"".equals(username)&&password!=null&&!"".equals(password)){
            username = Regex.checkReg(username);
            password = Regex.checkReg(password);
            User user = userDao.getUserByName(username);
            //password = EncryptUtil.md5Encrypt(password+(username+"wsn405").substring(0,7));
            if(user!=null&&password.equals(user.getPassword())){
                LogUtil.produceLogs(username,CommonValue.LOGIN_TYPE,CommonValue.LOGIN_LOGINFO,CommonValue.SUCCESS);
                UserView userView = new UserView();
                userView.setUsername(user.getUsername());
                userView.setRole(user.getRole());
                userView.setCreateTime(user.getCreateTime());
                JSONObject jsonObject = JSONObject.fromObject(userView);

                return JsonUtil.successJson(CommonValue.JSON_LOGIN_SUCCESS,jsonObject,null);
            }else {
                LogUtil.produceLogs(username,CommonValue.LOGIN_TYPE,CommonValue.LOGIN_LOGINFO,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_lOGIN_FAILED);
            }
        }else {

            LogUtil.produceLogs(username,CommonValue.LOGIN_TYPE,CommonValue.LOGIN_LOGINFO,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    /**
     * 业务层，添加用户
     * @param username 表单提供用户名
     * @param role 角色
     * @return 注册成功与否的状态,并返回注册用户的信息（JSONObject）
     */
    public String dealUserCreate(String username,String role,String myUsername) throws UnsupportedEncodingException {

        if(username!=null&&!"".equals(username)&&role!=null&&!"".equals(role)&&myUsername!=null&&!"".equals(myUsername)){
            username = Regex.checkReg(username);
            role = Regex.checkReg(role);
            role = "auditor".equals(role)?"auditor":"operator";
            myUsername = Regex.checkReg(myUsername);
            User user = userDao.getUserByName(username);
            if(user!=null){
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:"+role,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_USERNAME_EXIST);
            }else {
                user = new User();
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                user.setCreateTime(sdf.format(date));
                user.setUsername(username);
                //user.setPassword(CommonValue.DEFAULT_PASSWORD);
                user.setPassword(EncryptUtil.md5Encrypt(EncryptUtil.md5Encrypt(CommonValue.DEFAULT_PASSWORD+"scuwsn")+(username+"wsn405").substring(0,7)));
                user.setRole(role);
                boolean result = userDao.saveUser(user);
                if(result){
                    LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:"+role,CommonValue.SUCCESS);
                    return JsonUtil.successJson(CommonValue.JSON_CREATE_USER_SUCCESS, null,null);
                }else {
                    LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:"+role,CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
                }
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:"+role,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    public String dealAdminCreate(String username) throws UnsupportedEncodingException {

        if(username!=null&&!"".equals(username)){
            username = Regex.checkReg(username);
            User user = userDao.getUserByName(username);
            if(user!=null){
                return JsonUtil.failedJson(CommonValue.JSON_USERNAME_EXIST);
            }else {
                user = new User();
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                user.setCreateTime(sdf.format(date));
                user.setUsername(username);
                user.setPassword(CommonValue.DEFAULT_PASSWORD);
                //user.setPassword(EncryptUtil.md5Encrypt(EncryptUtil.md5Encrypt(CommonValue.DEFAULT_PASSWORD+"scuwsn")+(username+"wsn405").substring(0,7)));
                user.setRole("admin");
                boolean result = userDao.saveUser(user);
                if(result){
                    LogUtil.produceLogs("*",CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:admin",CommonValue.SUCCESS);
                    return JsonUtil.successJson(CommonValue.JSON_CREATE_USER_SUCCESS, null,null);
                }else {
                    LogUtil.produceLogs("*",CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:admin",CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
                }
            }
        }else {
            LogUtil.produceLogs("*",CommonValue.CREATE_TYPE,CommonValue.CREATE_USER_LOGINFO+":"+username+",角色为:admin",CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 修改用户密码
     * @param username
     * @param formerPassword
     * @param newPassword
     * @param myUsername
     * @return
     */
    public String dealUserUpdate(String username,String formerPassword,String newPassword,String myUsername) throws UnsupportedEncodingException {
        if(username!=null&&!"".equals(username)&&formerPassword!=null&&!"".equals(formerPassword)&&newPassword!=null&&!"".equals(newPassword)&&myUsername!=null&&!"".equals(myUsername)){
            username = Regex.checkReg(username);
            formerPassword = Regex.checkReg(formerPassword);
            newPassword = Regex.checkReg(newPassword);
            myUsername = Regex.checkReg(myUsername);
            //旧的信息
            User user = userDao.getUserByName(username);
            System.out.println("old:"+formerPassword);
            if(user!=null){
                //判断原密码正确
                if(formerPassword!=null&&EncryptUtil.md5Encrypt(formerPassword+(username+"wsn405").substring(0,7)).equals(user.getPassword())){
                    if(newPassword!=null&&!newPassword.isEmpty()){
                        newPassword = EncryptUtil.md5Encrypt(newPassword+(username+"wsn405").substring(0,7));
                        user.setPassword(newPassword);
                        boolean result = userDao.updateUser(username,user);
                        if(result){
                            LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_USER_LOGINFO+":"+username,CommonValue.SUCCESS);
                            return JsonUtil.successJson(CommonValue.JSON_UPDATE_SUCCESS,null,null);
                        }else {
                            LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_USER_LOGINFO+":"+username,CommonValue.FAILED);
                            return JsonUtil.failedJson(CommonValue.JSON_UPDATE_FAILED);
                        }
                    }else {
                        LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_USER_LOGINFO+":"+username,CommonValue.FAILED);
                        return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
                    }
                }else {
                    LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_USER_LOGINFO+":"+username,CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_PASSWORD_FAILED);
                }

            }else {
                LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_USER_LOGINFO+":"+username,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_USERNAME_NOTEXIST);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_USER_LOGINFO+":"+username,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 处理单个用户信息查询
     * @param username
     * @return
     */
    public String dealOneUserFind(String username){
        //按username查询
        if(username!=null&&!username.isEmpty()){
            User user = userDao.getUserByName(username);
            UserView userView = new UserView();
            userView.setUsername(user.getUsername());
            userView.setRole(user.getRole());
            userView.setCreateTime(user.getCreateTime());
            JSONObject jsonObject = JSONObject.fromObject(userView);
            return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 条件查询多个用户
     * @param role
     * @param pageNum
     * @param pageSize
     * @return
     */
    public String dealUsersFindByRole(String role,String pageNum,String pageSize){

        //按角色查询
        List<User> list = userDao.listUsersByRole(role,pageNum,pageSize);
        List<UserView> userViewList = new ArrayList<>();
        for(User user : list){
            UserView userView = new UserView();
            userView.setUsername(user.getUsername());
            userView.setRole(user.getRole());
            userView.setCreateTime(user.getCreateTime());
            userViewList.add(userView);
        }
        JSONArray jsonArray = JSONArray.fromObject(userViewList);
        return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS, null, jsonArray);
    }

    /**
     * 查询所有用户
     * @param pageNum
     * @param pageSize
     * @return
     */
    public String dealAllUsersFind(String pageNum,String pageSize){
        List<User> allList = userDao.listAllUsers(pageNum,pageSize);
        List<UserView> userViewList = new ArrayList<>();
        for(User user : allList){
            UserView userView = new UserView();
            userView.setUsername(user.getUsername());
            userView.setRole(user.getRole());
            userView.setCreateTime(user.getCreateTime());
            userViewList.add(userView);
        }
        JSONArray jsonArray = JSONArray.fromObject(userViewList);
        return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,null,jsonArray);
    }


    /**
     * 删除用户
     * @param username
     * @return
     */
    public String dealUserDelete(String username,String myUsername){
        if(username!=null&&!"".equals(username)){
            boolean result = userDao.deleteUser(username);
            if(result){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_USER_LOGINFO+":"+username,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS, null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_USER_LOGINFO+":"+username,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_DELETE_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_USER_LOGINFO+":"+username,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

}
